package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    EditText etUsername,etPassword;
    Button btnLogin,btnResign;
    SharedPreferences preferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        etUsername=findViewById(R.id.etUsername);
        etPassword=findViewById(R.id.etPassword);
        btnLogin=findViewById(R.id.btnLogin);
        btnResign=findViewById(R.id.btnResign);

        preferences=this.getSharedPreferences("userData",MODE_PRIVATE);

        btnLogin.setOnClickListener(this);
        btnResign.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        SharedPreferences.Editor editor=preferences.edit();
        String username=etUsername.getText().toString().trim();
        String password=etPassword.getText().toString().trim();
        switch (v.getId()){
            case R.id.btnLogin:
            {
                if (preferences.getString(username,"").equals(password)){
                    Log.v("1",password);
                    Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(getApplicationContext(),ListActivity.class));
                }else {
                    Toast.makeText(this, "请检查您输入的用户名或者密码是否正确", Toast.LENGTH_SHORT).show();
                }
            }
            break;
            case R.id.btnResign:
            {
                if (preferences.getString(username,"").equals("")){
                    editor.putString(username,password);
                    editor.commit();
                    Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(this, "该用户名已被注册", Toast.LENGTH_SHORT).show();
                }

            }
            break;
        }
    }
}
